import axios from 'axios'
import { ERR_TIMEOUT } from 'api/config'
import { changeDataType, backLogin } from 'common/js/util'

axios.defaults.withCredentials = true
axios.defaults.validateStatus = status => (status >= 200 && status < 300) || status === ERR_TIMEOUT

export const ajaxGet = (url = '', data = {}, options = {}) => {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: data,
      ...options
    }).then(res => {
      if (res.status === ERR_TIMEOUT) {
        backLogin({ alertMessage: '登录超时，请重新登录' })
        return
      }
      resolve(res.data)
    }).catch(res => {
      resolve(res)
    })
  })
}

export const ajaxPost = (url = '', data = {}, options = {}, isFormData = true) => {
  return new Promise((resolve, reject) => {
    let obj = data
    if (isFormData) {
      obj = changeDataType(data)
    }
    axios.post(url, obj, options)
      .then(res => {
        // if (res.status === ERR_TIMEOUT) {
        //   backLogin({ alertMessage: '登录超时，请重新登录' })
        //   return
        // }
        resolve(res.data)
      })
      .catch(res => {
        resolve(res)
      })
  })
}
